<?php

namespace App\Services;

use Illuminate\Support\Facades\Auth;
use Modules\Base\Models\OrderNumber;
use Modules\Base\Repository\OrderNumberRepository;
use Modules\Warehouse\Models\Stash;
use Modules\Warehouse\Models\Storagelocation;

/**
 * 公共工具类
 * Class UnitService
 * @package App\Services
 */
class UnitService
{

    /**
     * 通用单据编号创建
     * @param $prefix
     * @return string
     */
    static public function createDocno($prefix,$onlyNum = false){

        $lockTag = 'WMS:DOCNO_INDEX_' . $prefix;
        $redisLock = new RedisLockService($lockTag,10);

        if(!$redisLock->lockLoop()){
            throw new \Exception('单号生成失败，请重试！');
        }

        //获取锁成功
        $today = date('Ymd');
        try{

            $orderNumber = OrderNumberRepository::getOrderNumberByPrefix($prefix);

            if(!$onlyNum){
                $no = $orderNumber >= 10000 ? $orderNumber : sprintf("%04d",$orderNumber);
                $orderNumber = $prefix . (substr($today,2) . $no);
            }
            return $orderNumber;
        }catch (\Exception $e){
            throw $e;
        } finally {
            //释放锁
            $redisLock->unlock();
        }
    }

    /**
     * 获取当前登录用户的id
     * @return int|string|null
     */
    static public function getUserId(){
        return Auth::guard(getGuardName())->id();
    }

    /**
     * 获取当前格式化的时间
     * @return false|string
     */
    static public function getNowTime(){
        return date('Y-m-d H:i:s');
    }

    /**
     * 根据库位代码获取库位和仓库信息
     * @param $code
     * @return |null
     */
    static public function getLocationByCode($code){
        return empty($code) ? null : Storagelocation::where('warehousecode',$code)->with('wms')->first();
    }

    /**
     *根据仓库编号获取仓库信息
     * @param $code
     * @return |null
     */
    static public function getWmsByCode($code){
        return empty($code) ? null : Stash::where('fnumber',$code)->first();
    }
}
